package com.example.Service.impl;

import com.example.mapper.UserMapper;
import com.example.model.User;
import com.example.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public Result register(String username, String phone, String password, String confirmPassword) {
        if (userMapper.findByUsername(username) != null) {
            return Result.error("用户名已存在");
        }
        if (userMapper.findByPhone(phone) != null) {
            return Result.error("该手机号已注册");
        }
        if (!password.equals(confirmPassword)) {
            return Result.error("两次输入的密码不一致");
        }
        User user = new User();
        user.setUsername(username);
        user.setPhone(phone);
        user.setPassword(password);
        userMapper.insert(user);
        return Result.success(null);
    }

    public Result loginByPhone(String phone, String password) {
        User user = userMapper.findByPhone(phone);
        if (user == null || !user.getPassword().equals(password)) {
            return Result.error("手机号或密码错误");
        }
        return Result.success(null);
    }

    public Result changePasswordByPhone(String phone, String oldPassword, String newPassword) {
        User user = userMapper.findByPhone(phone);
        if (user == null || !user.getPassword().equals(oldPassword)) {
            return Result.error("旧密码错误");
        }
        int count = userMapper.updatePassword(user.getUsername(), newPassword);
        return count > 0 ? Result.success(null) : Result.error("密码更新失败");
    }

    public Result forgetPassword(String phone, String newPassword) {
        User user = userMapper.findByPhone(phone);
        if (user == null) {
            return Result.error("该手机号未注册");
        }
        int count = userMapper.updatePassword(user.getUsername(), newPassword);
        return count > 0 ? Result.success(null) : Result.error("密码重置失败");
    }

    // 根据手机号获取用户名
    public String getUsernameByPhone(String phone) {
        User user = userMapper.findByPhone(phone);
        if (user != null) {
            return user.getUsername();
        }
        return null;
    }

    // 根据手机号修改用户名
    public Result updateUsernameByPhone(String phone, String newUsername) {
        User user = userMapper.findByPhone(phone);
        if (user == null) {
            return Result.error("该手机号未注册");
        }
        int count = userMapper.updateUsernameByPhone(phone, newUsername);
        return count > 0 ? Result.success(null) : Result.error("用户名更新失败");
    }

    // 注销用户
    public Result deleteUser(String phone) {
        int count = userMapper.deleteUserByPhone(phone);
        return count > 0? Result.success(null) : Result.error("注销失败，该手机号可能不存在");
    }



}